package service

import (
	"encoding/json"
	"fmt"
	"net/http"
	"we-account-api/config"
)

type wechatService struct{}

var WechatService = new(wechatService)

type WXLoginResponse struct {
	OpenID     string `json:"openid"`
	SessionKey string `json:"session_key"`
	UnionID    string `json:"unionid"`
	ErrCode    int    `json:"errcode"`
	ErrMsg     string `json:"errmsg"`
}

func (s *wechatService) Code2Session(code string) (*WXLoginResponse, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		config.GlobalConfig.Wechat.AppID,
		config.GlobalConfig.Wechat.AppSecret,
		code,
	)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var wxResp WXLoginResponse
	if err := json.NewDecoder(resp.Body).Decode(&wxResp); err != nil {
		return nil, err
	}

	if wxResp.ErrCode != 0 {
		return nil, fmt.Errorf("微信登录失败: %s", wxResp.ErrMsg)
	}

	return &wxResp, nil
}
